package com.mf.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mf.entity.PurchaseRecord;
import com.mf.result.Result;
import com.mf.service.IPurchaseRecordService;
import com.mf.vo.PurchaseRecordVo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;


/**
*  前端控制器
*
* @author mf
* @since 2024-09-08
*/
@RestController
@RequestMapping("/purchaseRecord")
public class PurchaseRecordController {
    @Resource
    private IPurchaseRecordService purchaseRecordService;

    /**
     * 删除历史记录
     */
    @GetMapping("/deleteAllDateScope")
    public void deleteAllDateScope() {
        purchaseRecordService.remove(null);
    }

    /**
     * 计算盈利
     */
    @GetMapping("/calculateProfit")
    public Result<BigDecimal> calculateProfit(@RequestParam("year") String year) {
        final LambdaQueryWrapper<PurchaseRecord> wrapper = new LambdaQueryWrapper<>();
        if(year != null){
            wrapper.like(PurchaseRecord::getBuyDate, year);
        }
        final List<PurchaseRecord> list = purchaseRecordService.list(wrapper);
        BigDecimal price = new BigDecimal("100");
        for (PurchaseRecord purchaseRecord : list) {
            // 将1转换为BigDecimal
            BigDecimal one = BigDecimal.ONE;

            // 将total除以100转换为BigDecimal计算，并且设置小数点后两位（根据需要调整）
            BigDecimal fraction = BigDecimal.valueOf(purchaseRecord.getProfit()).divide(BigDecimal.valueOf(100), 2,
                    RoundingMode.HALF_UP);
            // 加上1
            BigDecimal sum = one.add(fraction);
            // 计算新的资本值
            BigDecimal newCapital = price.multiply(sum);
            // 去除小数部分
            price = newCapital.setScale(0, RoundingMode.DOWN);
        }
        return Result.success(price);
    }

    /**
     * 分页查询股票的K线图，并标识对应的买入卖出点
     */
    @GetMapping("/findAll")
    public Result<List<PurchaseRecordVo>> findAll(@RequestParam("pageNum") Integer pageNum,
                                                  @RequestParam("pageSize") Integer pageSize) {
        return Result.success(purchaseRecordService.listPage(pageNum, pageSize));
    }


}
